/**
 * 本地存储工具类
 * 用于保存用户的心语历史和AI响应
 */

export const STORAGE_KEYS = {
  HISTORY: 'xinyu_guoyun_history',
  SETTINGS: 'xinyu_guoyun_settings'
}

/**
 * 保存心语历史记录
 * @param {Object} record - 包含用户输入和AI响应的记录
 */
export const saveHistory = (record) => {
  try {
    const history = getHistory()
    const newRecord = {
      id: Date.now(),
      timestamp: new Date().toISOString(),
      ...record
    }
    
    history.unshift(newRecord)
    
    // 只保留最近20条记录
    const limitedHistory = history.slice(0, 20)
    
    localStorage.setItem(STORAGE_KEYS.HISTORY, JSON.stringify(limitedHistory))
    return true
  } catch (error) {
    console.error('保存历史记录失败:', error)
    return false
  }
}

/**
 * 获取心语历史记录
 * @returns {Array} 历史记录数组
 */
export const getHistory = () => {
  try {
    const history = localStorage.getItem(STORAGE_KEYS.HISTORY)
    return history ? JSON.parse(history) : []
  } catch (error) {
    console.error('读取历史记录失败:', error)
    return []
  }
}

/**
 * 删除单个历史记录
 * @param {string|number} recordId - 记录ID
 */
export const deleteHistoryRecord = (recordId) => {
  try {
    const history = getHistory()
    const filteredHistory = history.filter(record => record.id !== recordId)
    localStorage.setItem(STORAGE_KEYS.HISTORY, JSON.stringify(filteredHistory))
    return true
  } catch (error) {
    console.error('删除历史记录失败:', error)
    return false
  }
}

/**
 * 清空历史记录
 */
export const clearHistory = () => {
  try {
    localStorage.removeItem(STORAGE_KEYS.HISTORY)
    return true
  } catch (error) {
    console.error('清空历史记录失败:', error)
    return false
  }
}

/**
 * 保存用户设置
 * @param {Object} settings - 用户设置对象
 */
export const saveSettings = (settings) => {
  try {
    localStorage.setItem(STORAGE_KEYS.SETTINGS, JSON.stringify(settings))
    return true
  } catch (error) {
    console.error('保存设置失败:', error)
    return false
  }
}

/**
 * 获取用户设置
 * @returns {Object} 用户设置对象
 */
export const getSettings = () => {
  try {
    const settings = localStorage.getItem(STORAGE_KEYS.SETTINGS)
    return settings ? JSON.parse(settings) : {
      theme: 'default',
      autoSave: true,
      showHistory: true
    }
  } catch (error) {
    console.error('读取设置失败:', error)
    return {
      theme: 'default',
      autoSave: true,
      showHistory: true
    }
  }
}

/**
 * 导出历史记录为JSON文件
 */
export const exportHistory = () => {
  try {
    const history = getHistory()
    const dataStr = JSON.stringify(history, null, 2)
    const dataBlob = new Blob([dataStr], { type: 'application/json' })
    
    const link = document.createElement('a')
    link.href = URL.createObjectURL(dataBlob)
    link.download = `心语国韵_历史记录_${new Date().toISOString().split('T')[0]}.json`
    link.click()
    
    return true
  } catch (error) {
    console.error('导出历史记录失败:', error)
    return false
  }
}

export default {
  saveHistory,
  getHistory,
  deleteHistoryRecord,
  clearHistory,
  saveSettings,
  getSettings,
  exportHistory
}
